<?php

namespace App\Trip\Plane;

use Illuminate\Support\Facades\Cache;
use Maatwebsite\Excel\Facades\Excel;

class PlaneCities
{
    private array  $seeder;
    private string $city_code_column;
    private string $name_uy_column;
    private string $name_column;
    private string $adcode_column;
    private string $name_uy_letter_column;

    public function __construct($refresh = false)
    {

        $this->city_code_column      = "0";
        $this->name_column           = "1";
        $this->adcode_column         = "3";
        $this->name_uy_column        = "5";
        $this->name_uy_letter_column = "6";
        $ck                          = "Plane:PlaneCities";
        if (Cache::has($ck) && !$refresh) {
            $seeder = Cache::get($ck);
        } else {
            $data   = Excel::toArray(collect(), storage_path('plane/seeds/plane_cities.xlsx'));
            $seeder = $data[0];
            unset($seeder[0]);
            Cache::forever($ck, $seeder);
        }
        $this->seeder = collect($seeder)->filter(fn($row) => !is_null($row[3]))->toArray();

    }

    /**
     * 全称 维语
     * @param string $city_code
     * @return string
     */
    public function getCityNameUyByCode(string $city_code): string
    {
        return $this->getDataByCode($city_code)[$this->name_uy_column];
    }

    private function getDataByCode(string $city_code)
    {
        if (!$city_code) {
            return [];
        }
        $ck = "Plane:PlaneCities:{$city_code}";
        if (Cache::has($ck)) {
            return Cache::get($ck);
        } else {
            $ret = collect($this->seeder)->firstWhere($this->city_code_column, $city_code);
            $ret && Cache::forever($ck, $ret);
            return $ret;
        }
    }

    /**
     * 简称 维语
     * @param string $city_code
     * @return string
     */
    public function getNameUyLetterByCode(string $city_code): string
    {
        return $this->getDataByCode($city_code)[$this->name_uy_letter_column];
    }

    /**
     * 航司全称
     * @param string $city_code
     * @return string
     */
    public function getCityNameByCode(string $city_code): string
    {
        return $this->getDataByCode($city_code)[$this->name_column] ?? '';
    }

    /**
     * 航司简称
     * @param string $city_code
     * @return string
     */
    public function getCityAdcodeByCode(string $city_code): string
    {
        return $this->getDataByCode($city_code)[$this->adcode_column] ?? '';
    }
}